import { Component, Input } from '@angular/core';
import { List } from '../../_common/_model/list';
import { ListService } from '../../_common/_service/list.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { Router } from '@angular/router';

@Component({
  selector: 'app-sider-contextmenu',
  templateUrl: './contextmenu.component.html',
  styleUrls: ['./contextmenu.component.less']
})
export class SiderContextmenuComponent {
  @Input() currentList: List;
  @Input() visible: boolean;
  @Input() x: number;
  @Input() y: number;

  constructor(
    private _router: Router,
    private _listService: ListService,
    private _confirm: NzModalService,
    private _message: NzMessageService) { }

  get locationCSS() {
    return {
      'display': this.visible ? 'block' : 'none',
      'left': this.x + 'px',
      'top': this.y + 'px'
    };
  }

  deleteList() {
    const ctx = this;
    this._confirm.confirm({
      title: `您确定要删除清单（${this.currentList.title}）吗？`,
      onOk() {
        ctx._listService.deleteList(ctx.currentList.id)
          .subscribe(
            next => {
              const index = ctx._listService.lists.findIndex(u => u.id === ctx.currentList.id);
              ctx._listService.lists.splice(index, 1);
              ctx._message.success('删除成功');
              setTimeout(() => {
                ctx._router.navigate(['/my-day']);
              }, 1000);
            },
            err => {
              const { msg, code } = err;
              if (code && code === 4005) {
                ctx._message.error('清单不存在');
              } else {
                ctx._message.error(msg);
              }
          });
      },
      onCancel() {}
    });
  }
}
